## This program generates Figure 7 from "Financial Constraints, Sectoral Heterogeneity,
##  and the Cyclicality of Investment" by Cooper Howes

##### Step 0: Preliminaries #####

## Clear variables and data
rm(list=ls())

## Load packages
library(tidyverse)

##### Step 1: Load data #####

## Load impulse responses from model (created in Dynare file "baseline_model.mod")
irfdata <- t(read.csv("irfs/shock_irfs_baseline.csv",header=F))

## Extract names and relabel
colnames(irfdata) <- irfdata[1,]
rownames(irfdata) <- NULL
irfdata <- irfdata[-1,]


## Horizontal axis labels
qtrs <- 0:16

##### Step 2: Plot user cost and durable price IRFs (left panel) #####

## Create new window
windows(width=8,height=5)
par(oma=c(5.5,1,0,1))

## Set y-axis range
price_range <- c(-0.4,0.3)

## Plot IRFs 
par(mar = c(1,3,1,1))
plot(x=qtrs,y=irfdata[,"p_d_e_m"],col="orange",type="b",pch=3,lwd=4,ylim=price_range,ann=FALSE,axes=FALSE,frame=TRUE)
lines(x=qtrs,y=irfdata[,"mpk_d_e_m"],type="b",pch=1,col="blue",lwd=4)
lines(x=qtrs,y=irfdata[,"mpk_n_e_m"],type="b",pch=2,col="red",lwd=4)
abline(a=0,b=0,col="black",lwd=1)
axis(1,cex.axis=1.25)
axis(2,cex.axis=1.25,at=pretty(price_range),lab=paste0(pretty(price_range)*100, "%"),las=TRUE)
mtext("Quarters after shock", side=1, line=2.5,cex=1.25)

## Add legend
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
legend(x="bottom",inset=0,legend=c("Durable price","Durable user cost","Nondurable user cost"),
       lwd=2,lty=1,pch=c(3,1,2),col=c("orange","blue","red"),cex=1.2,horiz=TRUE)


##### Step 3: Plot lagrange multiplier on financial constraint mu (right panel) #####


## Create new window
windows(width=8,height=5)
par(oma=c(5.5,1,0,1))

## Set y-axis range
mu_range <- c(-0.1,5)

## Plot IRF
par(mar = c(1,3,1,1))
plot(x=qtrs,y=irfdata[,"mu_e_m"],col="forestgreen",type="b",pch=4,lwd=4,ylim=mu_range,ann=FALSE,axes=FALSE,frame=TRUE)
abline(a=0,b=0,col="black",lwd=1)
axis(1,cex.axis=1.25)
axis(2,cex.axis=1.25,at=pretty(mu_range),lab=paste0(pretty(mu_range)*100, "%"),las=TRUE)
mtext("Quarters after shock", side=1, line=2.5,cex=1.25)

## Add legend
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
legend(x="bottom",inset=0,legend=c("Financial constraint"),
       lwd=2,lty=1,pch=c(4),col=c("forestgreen"),cex=1.2,horiz=TRUE)

